import Vue from 'vue'
import VueRouter from 'vue-router'
import store from "../store"

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err);
}

Vue.use(VueRouter)
const routes = [
  {
    path: '/',
    redirect: '/welcome',
    name: "custom",
    meta: {requiresAuth: true},
    component: () => import('@/components/system/admin.vue'),
    children: [{
      path: '/welcome',
      name: 'welcome',
      component: () => import('@/components/system/welcome.vue')
    }, {
      path: '/main',
      name: 'main',
      component: () => import('@/components/deprecated/main.vue')
    }, {
      path: "/editArticle",
      name: "editArticle",
      component: () => import('@/components/message/article/edit.vue')
    }, {
      path: "/editNotice",
      name: "editNotice",
      component: () => import('@/components/message/notice/edit.vue')
    }, {
      path: "/label",
      name: "label",
      component: () => import('@/components/message/label/index.vue')
    }
    ]
  },
  {
    path: '/verify',
    name: 'verify',
    component: () => import('@/components/system/verify.vue')
  }
]

const router = new VueRouter({
  base: "/admin/",
  mode: "history",
  routes: routes,
  scrollBehavior(to, from, savedPosition) {
    return {x: 0, y: 0}
  }
})

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!Boolean(localStorage.getItem("adminToken"))) {
      next({
        path: '/verify',
        query: {redirect: to.fullPath}
      });
    } else {
      next();
    }
  } else if (!to.name) {
    let list = store.state.routeList
    if (list.length > 0) {
      list.map(item => {
        router.addRoute('custom', item)
      })
    } else {
      let ary = JSON.parse(localStorage.getItem('routers'))
      ary.map(item => {
        if (item.child.length > 0) {
          item.child.map(tr => {
            router.addRoute('custom', {
              path: tr.path,
              name: Symbol(tr.componentName),
              component: () => import(`@/components${tr.component}`),
            })
          })
        } else {
          if (item.component) {
            let obj = {
              path: item.path,
              name: Symbol(item.componentName),
              component: () => import(`@/components${item.component}`),
            }
            router.addRoute('custom', obj)
          }else {
            let obj = {
              path: item.path,
              name: Symbol(item.componentName),
              component: () => import('@/components/system/comingSoon.vue'),
            }
            router.addRoute('custom', obj)
          }
        }
      })
    }
    next({...to, replace: true})
  } else {
    next();
  }
})

export default router
